// pages/clock/clock.js
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
const ctx = wx.createCanvasContext('myCanvas')
const app = getApp()
var second = 0
var minute = 0
var second1 = 0
var minute1 = 0
var indextime = 0
var timer
Page({
  data: {
    tempImgPath: '',
    imageurl: '',
    soundurl: '',
    textcontent: '',
    spot: {},
    imageFilePath: '',
    soundFilePath: '',
    soundplay: 'none',
    second: 0,
    minute: 0,
    second1: 0,
    minute1: 0,
    show: false,
    textshow: true,
    pica: '../../img/record1.png',
    pic: '../../img/record2.png',
    active: false,
    pop: false,
    place: false,
    success: true,
    con1: 'block',
    con2: 'none',
    box: true,
    scal: 1,
    clock_info: ''
  },
  onLoad: function (options) {
    var id = options.spotid
    var page = this
    console.log(app.globalData.userInfo)
    wx.getSystemInfo({
      success: function (res) {
        page.setData({
          scale: res.screenWidth / 750,
          timestyle: '',
          circlestyle: ''
        })
      }
    })
    wx.showLoading({
      title: 'Loading',
      mask: true
    })
    console.log(options.spotid)

    app.util.request({
      url: 'entry/wxapp/GetSpot',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      data: {
        dataid: id
      },
      success: function (res) {
        wx.hideLoading()
        console.log(res.data)
        if (res.data.code == 200) {
          page.setData({
            spot: res.data.data
          })
        } else {
          wx.showToast({
            title: '网络错误！',
            icon: 'none',
            duration: 2000,
            mask: true
          })
        }
      },
      fail: function () {
        wx.hideLoading()
      }
    })
    this.conShow()
  },
  showAc: function (e) {
    var that = this //获取上下文
    //选择图片
    wx.chooseImage({
      count: 1, // 默认9，这里显示一次选择相册的图片数量
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera', 'album'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        console.log(res)
        console.log(res.tempFiles[0].path)
        var imageFilePath = res.tempFiles[0].path
        //显示
        that.setData({
          imageFilePath: res.tempFiles[0].path
        })
      }
    })
  },

  //录音按钮控制
  soundcontrol: function () {
    var page = this
    var active = page.data.active
    console.log('active' + active)
    if (active) {
      page.bindtouchend()
    } else {
      page.bindtouchstart()
    }
  },
  //开始录音
  bindtouchstart: function () {
    var page = this
    console.log('bindtouchstart')
    indextime = 0
    second = 0
    minute = 0
    second1 = 0
    minute1 = 0
    page.Countdown(indextime, page)
    page.startrecorderManager()
    page.setData({
      active: true
    })
    wx.setNavigationBarTitle({
      title: '录音中...' //页面标题为路由参数
    })
  },

  //停止录音
  bindtouchend: function () {
    var page = this
    console.log('bindtouchend')
    page.stoprecorderManager()
    page.setData({
      active: false
    })
    page.timenum()
    wx.setNavigationBarTitle({
      title: '景区打卡' //页面标题为路由参数
    })
  },

  // 关闭倒计时
  timenum: function () {
    clearTimeout(timer)
  },

  //停止录音
  stoprecorderManager: function () {
    var page = this
    recorderManager.stop()
    recorderManager.onStop(res => {
      this.tempFilePath = res.tempFilePath
      console.log('停止录音', res)
      const { tempFilePath } = res
      page.setData({
        soundFilePath: tempFilePath,
        soundplay: ''
      })
    })
  },
  //录音方法
  startrecorderManager: function () {
    var page = this
    const options = {
      title: 'text',
      duration: 20000, //指定录音的时长，单位 ms    sampleRate: 16000,//采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 48000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50 //指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options)
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    //错误回调
    recorderManager.onError(res => {
      console.log(res)
    })
  },

  // 倒计时
  Countdown: function () {
    var page = this
    indextime++
    timer = setTimeout(function () {
      second1++
      console.log('----Countdown----' + second1)
      if (second1 == 10) {
        second1 = 0
        second++
        if (second == 6) {
          second = 0
          minute1++
          if (minute1 == 10) {
            minute1 = 0
            minute++
          }
        }
      }
      page.setData({
        second: second,
        minute: minute,
        second1: second1,
        minute1: minute1
      })
      page.Countdown()
    }, 1000)
  },

  //播放录音
  soundplay: function () {
    var page = this
    console.log('soundFilePath' + page.data.soundFilePath)
    if (page.data.soundFilePath == '') {
      wx.showToast({
        title: '请录音完成',
        icon: 'none',
        duration: 2000
      })
    } else {
      var page = this
      innerAudioContext.autoplay = true;
      innerAudioContext.src = page.data.soundFilePath
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
      innerAudioContext.onError(res => {
        console.log(res.errMsg)
        console.log(res.errCode)
      })
    }
  },

  //获取输入的值
  voteTitle: function (e) {
    this.setData({
      textcontent: e.detail.value
    })
  },

  //保存录音 上传
  clockupload: function (e) {
    var page = this
    //console.log(page.data.textcontent)
    wx.showLoading({
      title: 'Loading',
      mask: true
    })
    var res = page.data.soundFilePath
    if (page.data.textcontent == '') {
      wx.showToast({
        title: '请输入内容！',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    if (res == '') {
      wx.showToast({
        title: '请录音！',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    if (page.data.imageFilePath == '') {
      wx.showToast({
        title: '请上传图片！',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    wx.uploadFile({
      url: app.data.path,
      filePath: res, //上传的文件本地地址
      name: 'file',
      formData: {
        openid: app.openid,
        op: 'sound'
      },
      //附近数据，这里为路径
      success: function (res) {
        console.log(res)
        var reut = JSON.parse(res.data)
        if (reut.code == 200) {
          page.setData({
            soundurl: reut.data
          })
          wx.uploadFile({
            url: app.data.path,
            filePath: page.data.imageFilePath, //上传的文件本地地址
            name: 'file',
            formData: {
              openid: app.openid,
              op: 'image'
            },
            //附近数据，这里为路径
            success: function (res) {
              console.log(JSON.parse(res.data))
              var info = JSON.parse(res.data)
              if (info.code == 200) {
                page.setData({
                  imageurl: info.data
                })
                app.util.request({
                  //url: 'entry/wxapp/Clockupload',
                  url: app.data.path,
                  header: {
                    'content-type': 'application/x-www-form-urlencoded'
                  },
                  method: 'POST',
                  data: {
                    openid: app.openid,
                    imageurl: page.data.imageurl,
                    soundurl: page.data.soundurl,
                    textcontent: page.data.textcontent,
                    avatarUrl: app.globalData.userInfo.avatarUrl,
                    nickname: app.globalData.userInfo.nickName,
                    spotid: page.data.spot.id,
                    soundtime: indextime,
                    op: 'clockupload'
                  },
                  success: function (res) {
                    wx.hideLoading()
                    console.log(res.data)
                    if (res.data.code == 200) {
                      page.setData({
                        textshow: !page.data.textshow,
                        clock_info: res.data.data,
                        pop: true,
                        con1: 'blcok',
                        con2: 'none'
                      })
                      page.preview(res.data.data)
                    } else {
                      wx.showToast({
                        title: '网络错误！',
                        icon: 'none',
                        duration: 2000,
                        mask: true
                      })
                    }
                  },
                  fail: function () {
                    wx.hideLoading()
                  }
                })
              }
            },
            fail: function () {
              wx.hideLoading()
              wx.showToast({
                title: '请选择图片',
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      },
      fail: function () {
        wx.hideLoading()
        wx.showToast({
          title: '请录音完成',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  onClose: function () {
    console.log('2333')
  },
  onCancel: function () {
    this.setData({
      show: false
    })
  },
  onPopup: function () {
    this.setData({
      pop: true,
      place: true,
      box: false
    })
  },
  clPopup: function () {
    this.setData({
      pop: false,
      place: false,
      box: true
    })
  },
  conShow: function () {
    if (this.data.success == true) {
      this.setData({
        con1: 'blcok',
        con2: 'none'
      })
    }
    if (this.data.success == false) {
      this.setData({
        con1: 'none',
        con2: 'block'
      })
    }
  },

  //co
  //画文字
  preview: function (data) {
    //文字
    console.log('jinlaile ')
    wx.showLoading({
      title: 'Loading',
      mask: true
    })
    var page = this
    drawNetImage(data, page, app)
  },

  go_myline: function () {
    wx.navigateTo({
      url: '../line/line'
    })
  },

  //保存本地
  btn_bc: function () {
    wx.showLoading({
      title: 'Loading',
      mask: true
    })
    var page = this
    wx.saveImageToPhotosAlbum({
      //保存生成的图片到手机相册里
      filePath: page.data.tempImgPath,
      success(res) {
        wx.hideLoading()
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        })
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 2000)
      },
      fail: function (err) {
        console.log(err)
        wx.showToast({
          title: '保存失败',
          icon: 'success',
          duration: 2000
        })

        if (err.errMsg === 'saveImageToPhotosAlbum:fail auth deny') {
          console.log('当初用户拒绝，再次发起授权')
          wx.authorize({
            scope: 'scope.writePhotosAlbum'
          })
        }
      },

      complete(res) {
        wx.hideLoading()
      }
    })
  }
})

function drawNetImage(data, page, app) {
  var txbkurl = app.data.iconpath + '/addons/maixun_wuxilvyou/icon/txbk.png'
  var bgurl = ''
  var qrurl = ''
  var avatarUrl = ''
  var txbk = ''
  console.log(
    'handimg:-->' +
    data.handimage +
    'qrcode:-->' +
    data.codeimg +
    'content:-->' +
    data.content
  )
  var titleHeight = 20 // 标题的高度
  var canvasWidth = 544 * page.data.scale //计算canvas的宽度
  var initHeight = 340 * page.data.scale + 20
  wx.getImageInfo({
    src: txbkurl, //请求的网络图片路径
    success: function (res) {
      txbk = res.path
      wx.getImageInfo({
        src: data.avatarUrl, //请求的网络图片路径
        success: function (res) {
          avatarUrl = res.path
          wx.getImageInfo({
            src: app.data.imgpath + data.handimage, //请求的网络图片路径
            success: function (res) {
              bgurl = res.path
              var picscale = 0.95
              var sbl = res.width / res.height
              if (sbl > picscale) {
                var th = res.height
                var tw = th * picscale
                var tx = (res.width - tw) / 2
                var ty = 0
              } else {
                var tw = res.width
                var th = tw / picscale
                var tx = 0
                var ty = (res.height - th) / 2
              }
              wx.getImageInfo({
                src: data.codeimg, //请求的网络图片路径
                success: function (res) {
                  qrurl = res.path
                  ctx.setFillStyle('white')
                  ctx.fillRect(
                    0,
                    0,
                    544 * page.data.scale,
                    715 * page.data.scale
                  )
                  ctx.drawImage(
                    bgurl,
                    0,
                    0,
                    544 * page.data.scale,
                    340 * page.data.scale
                  )
                  ctx.drawImage(
                    qrurl,
                    544 * page.data.scale - 90,
                    715 * page.data.scale - 90,
                    90,
                    90
                  )
                  // var d = 55;
                  // var cx = 2 + 55;
                  // var cy = 715 * page.data.scale - 65 + 55;
                  // ctx.arc(cx, cy, 55, 0, 2 * Math.PI);
                  // ctx.clip();
                  ctx.drawImage(
                    avatarUrl,
                    2,
                    715 * page.data.scale - 65,
                    55,
                    55
                  )
                  ctx.drawImage(txbk, 2, 715 * page.data.scale - 65, 55, 55)
                  //ctx.drawImage(avatarUrl, 2, 715 * page.data.scale - 65, 55, 55)
                  ctx.setFontSize(14)
                  ctx.fillStyle = '#858585'
                  ctx.lineWidth = 1
                  drawText(
                    ctx,
                    data.content,
                    initHeight,
                    titleHeight,
                    canvasWidth - 20,
                    data,
                    page
                  ) // 调用行文本换行函数
                  ctx.draw(false, function () {
                    console.log('aaaa')
                    Okgenerate(page, data)
                  })
                }
              })
            }
          })
        }
      })
    }
  })
}

function drawText(ctxx, str, initHeight, titleHeight, canvasWidth, data, page) {
  var lineWidth = 0
  var lastSubStrIndex = 0 //每次开始截取的字符串的索引
  console.log(str.length)
  str = str.substring(0, 65) + '....'
  for (let i = 0; i < str.length; i++) {
    lineWidth += ctxx.measureText(str[i]).width
    if (lineWidth > canvasWidth) {
      ctxx.fillText(str.substring(lastSubStrIndex, i), 0, initHeight) //绘制截取部分
      initHeight += 22 //20为字体的高度
      lineWidth = 0
      lastSubStrIndex = i
      titleHeight += 30
    }
    if (i == str.length - 1) {
      //绘制剩余部分
      ctxx.fillText(str.substring(lastSubStrIndex, i + 1), 0, initHeight)
    }
  }
  ctx.setFontSize(16)
  ctx.fillStyle = '#636161'
  ctx.fillText(data.nickname, 75, 715 * page.data.scale - 45)
  ctx.setFontSize(12)
  ctx.fillStyle = '#bcbbbb'
  ctx.fillText(data.crTime, 75, 715 * page.data.scale - 15)

  // 标题border-bottom 线距顶部距离
  titleHeight = titleHeight + 10
  return titleHeight
}

//生成图片
function Okgenerate(page, data) {
  //生成图片方法
  wx.canvasToTempFilePath({
    //生成图片
    x: 0,
    y: 0,
    quality: 1,
    fileType: 'jpg',
    canvasId: 'myCanvas',
    success: function (res) {
      console.log('lala-->')
      console.log(res.tempFilePath)
      page.setData({
        tempImgPath: res.tempFilePath
      })
      wx.uploadFile({
        url: app.data.path,
        filePath: res.tempFilePath, //上传的文件本地地址
        name: 'file',
        formData: {
          openid: app.openid,
          op: 'clock',
          id: data.id
        },
        //附近数据，这里为路径
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
        }
      })
    }
  })
}
